package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<IPage<DishDto>> page(int page, int pageSize, String name) {
        IPage<Dish> pageInfo = new Page(page, pageSize);
        IPage<DishDto> pages = new Page(page, pageSize);
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        query.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, query);
        BeanUtils.copyProperties(pageInfo, pages, "records");
        //遍历集合封装数据
        List<DishDto> dishDtoList = pageInfo.getRecords().stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //分类名称填充
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        pages.setRecords(dishDtoList);
        return R.success(pages);
    }

    /**
     * 新增菜品信息
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("dto:==>{}", dishDto);
        dishService.saveWithFlavors(dishDto);
        //清理某个分类下的缓存信息
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 获取菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getWithFlavors(@PathVariable Long id) {
        DishDto dishDto = dishService.getWithFlavors(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateWithFlavor(@RequestBody DishDto dishDto) {
        log.info("dishDto: ==> {}", dishDto);
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存信息
        //String key = "dish_*";
        //redisTemplate.delete(key);
        //清理某个分类下的缓存信息
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 修改状态停售起售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, @RequestParam List<Long> ids) {
        log.info("status: {} ", status == 0 ? "停售" : "起售");
        dishService.updateStatus(status, ids);
        return R.success("修改状态成功");
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:===>", ids);
        dishService.delete(ids);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在，直接返回，无需查询数据库
        if(dishDtoList != null && dishDtoList.size() > 0){
            return R.success(dishDtoList);
        }
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis

        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish.getName())
                .orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                //查询起售状态
                .eq(Dish::getStatus,1);
        List<Dish> dishList = dishService.list(query);
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish.getName())
                .orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                //查询起售状态
                .eq(Dish::getStatus,1);
        List<Dish> dishList = dishService.list(query);
        return R.success(dishList);
    }*/
}
